package cao.oschina.function.tweet;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import cao.oschina.R;
import cao.oschina.api.URLs;
import cao.oschina.app.AppContext;
import cao.oschina.bean.Comment;
import cao.oschina.bean.Like;
import cao.oschina.bean.Tweet;
import cao.oschina.ui.Main;
import cao.oschina.util.FileUtils;
import cao.oschina.util.TimeUtil;
import cao.oschina.widget.PushDownListView;
import cao.oschina.widget.RefreshView;
import hd.util.ToastUtil;
import hd.util.adapter.BaseViewHolder;
import hd.util.adapter.UniAdapter;
import hd.util.http.HttpClient;
import hd.util.http.HttpRequestListener;
import hd.util.http.HttpResponse;
import hd.util.load.ImageLoader;
import hd.util.widget.listview.BasePushDownListView;

/**
 * 动弹
 * <p/>
 * Created by Haidy on 15/4/4.
 */
public class TweetFunction {

    public static final int TYPE_LATEST = 0;
    public static final int TYPE_HOT = -1;
    public static final int TYPE_ME = 2;

    private final View view;
    private final AppContext app;
    private final Main main;
    private final int type;

    private boolean isLoading = false;
    private boolean getAll = false;//是否获取全部列表

    private PushDownListView listView;
    private TweetAdapter adapter;
    private int pageIndex = 0;

    public TweetFunction(View view, Main main, int type) {
        this.view = view;
        this.main = main;
        this.app = main.app;
        this.type = type;
        initView();
        initData();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        listView = (PushDownListView) view.findViewById(R.id.tweet_list_view);
        adapter = new TweetAdapter(app);
        listView.setAdapter(adapter);
        listView.setOnRefreshListener(new PushDownListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isLoading) {
                    getAll = false;
                    pageIndex = 0;
                    loadData(true);
                }
            }
        });
        listView.setOnLoadNextPageListener(new BasePushDownListView.OnLoadNextPageListener() {
            @Override
            public void onLoad() {
                if (!getAll && !isLoading) {
                    pageIndex++;
                    loadData(false);
                }
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (adapter.getItem(position - 1) != null) {
                    Intent intent = new Intent(view.getContext(), TweetDetail.class);
                    Tweet tweet = adapter.getItem(position - 1);
                    intent.putExtra("id", tweet.id);
                    intent.putExtra("body", tweet.body);
                    intent.putExtra("author", tweet.author);
                    intent.putExtra("authorid", tweet.authorid);
                    intent.putExtra("appclient", tweet.appclient);
                    intent.putExtra("commentCount", tweet.commentCount);
                    intent.putExtra("portrait", tweet.portrait);
                    intent.putExtra("pubDate", tweet.pubDate);
                    intent.putExtra("imgSmall", tweet.imgSmall);
                    intent.putExtra("imgBig", tweet.imgBig);
                    intent.putExtra("attach", tweet.attach);
                    intent.putExtra("likeCount", tweet.likeCount);
                    intent.putExtra("isLike", tweet.likeCount);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    view.getContext().startActivity(intent);
                    main.activityPushAnim();
                }
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        loadData(true);
    }

    /**
     * 加载数据
     *
     * @param refresh 刷新
     */
    private void loadData(final boolean refresh) {
        String url = getUrl();
        if (type == TYPE_ME && url == null) {
            remindLogin();
            return;
        }
        new HttpClient().httpGet(url, new HttpRequestListener() {

            @Override
            public void startRequest() {
                listView.setEnabled(false);
                isLoading = true;
            }

            @Override
            public void success(HttpResponse response) {
                List<Tweet> tweetList = Tweet.parser(response.text);
                if (refresh) {
                    adapter.setData(tweetList);
                } else {
                    if (adapter.getCount() != 0) {
                        adapter.remove(adapter.getCount() - 1);
                    }
                    if (tweetList.size() < 20) {
                        getAll = true;
                    }
                    adapter.addAllData(tweetList);
                }
                adapter.addData(null);
                listView.overHeadScroll();
                listView.setEnabled(true);
            }

            @Override
            public void failure(HttpResponse response) {
                ToastUtil.toastShort(response.info);
            }

            @Override
            public void end() {
                isLoading = false;
            }
        });
    }

    /**
     * 提醒登录
     */
    private void remindLogin() {

    }

    /**
     * 获取url
     *
     * @return url
     */
    private String getUrl() {
        if (type != TYPE_ME) {
            return URLs.TWEET_LIST + "?uid=" + type + "&pageIndex=" + pageIndex + "&pageSize=20";
        }
        String uid = app.getConfig().getUid();
        return uid == null ? null : URLs.TWEET_LIST + "?uid=" + uid + "&pageIndex=" + pageIndex + "&pageSize=20";
    }

    private class TweetAdapter extends UniAdapter<Tweet, ViewHolder> {

        private ImageLoader imageLoader;

        public TweetAdapter(Context context) {
            super(context);
            imageLoader = new ImageLoader();
            imageLoader.setImageRes(R.mipmap.ic_account_circle_grey600_36dp);
        }

        @Override
        public int getContentView() {
            return R.layout.tweet_list_item_view;
        }

        @Override
        public BaseViewHolder<Tweet, ViewHolder> getHolder() {
            return new BaseViewHolder<Tweet, ViewHolder>() {
                @Override
                public void loadData(ViewHolder holder, Tweet data, int position) {
                    if (data != null) {
                        if (holder.itemView.getVisibility() == View.GONE) {
                            holder.itemView.setVisibility(View.VISIBLE);
                            holder.nextPageView.setVisibility(View.GONE);
                            holder.refreshView.stopRotation();
                        }
                        holder.contentView.setText(data.body);
                        holder.authorView.setText(data.author);
                        holder.infoView.setText(TimeUtil.friendTime(data.pubDate) + getDevice(Integer.parseInt(data.appclient)));
                        holder.commentCountView.setText(data.commentCount);
                        loadHeadView(holder.headView, data.portrait);
                        // TODO thumb view
                        holder.thumbView.setVisibility(View.GONE);
//                        likeView(holder.thumbView, data.likeList);
                    } else {
                        if (holder.nextPageView.getVisibility() == View.GONE) {
                            holder.itemView.setVisibility(View.GONE);
                            holder.nextPageView.setVisibility(View.VISIBLE);
                            if (getAll) {
                                holder.refreshView.setVisibility(View.GONE);
                                holder.refreshTextView.setText(main.getString(R.string.get_all_data));
                            } else {
                                holder.refreshTextView.setText(main.getString(R.string.loading_next_pager));
                                holder.refreshView.setVisibility(View.VISIBLE);
                                holder.refreshView.startRotation();
                            }
                        }
                    }
                }

                /**
                 * 获取设备
                 * @param client 设备id
                 * @return string
                 */
                private String getDevice(int client) {
                    String str = " ";
                    if (client == Comment.CLIENT_ANDROID) {
                        return str + main.getString(R.string.android);
                    } else if (client == Comment.CLIENT_IPHONE) {
                        return str + main.getString(R.string.iphone);
                    } else if (client == Comment.CLIENT_WINDOWS_PHONE) {
                        return str + main.getString(R.string.windows_phone);
                    } else if (client == Comment.CLIENT_MOBILE) {
                        return str + main.getString(R.string.phone);
                    }
                    return "";
                }

                private void likeView(TextView thumbView, List<Like> likeList) {
                    String str = "";
                    if (likeList == null || likeList.size() == 0) {
                        thumbView.setVisibility(View.GONE);
                    } else {
                        thumbView.setVisibility(View.VISIBLE);
                        if (likeList.size() == 1) {
                            str = "<p color=\"007cff\">" + likeList.get(0) + "</p>觉得很赞";
                        } else {
                            for (Like like : likeList) {
                                str += "<p color=\"007cff\">" + like.name + "</p>、";
                            }
                            str = str.substring(0, str.length() - 1);
                            str += "等<p color=\"007cff\">" + likeList.size() + "人</p>觉得很赞";
                        }
                        thumbView.setText(str);
                    }
                }

                /**
                 * 头像
                 * @param headView headView
                 * @param portrait url
                 */
                private void loadHeadView(ImageView headView, String portrait) {
                    imageLoader.loadImage(portrait, headView, new ImageLoader.OnImageCacheLoaderListener() {
                        @Override
                        public String onSDCardCache(String url) {
                            return FileUtils.getHeadImagePath(main, url);
                        }
                    });
                }
            };
        }

        @Override
        public ViewHolder initViewHolder(View convertView) {
            return new ViewHolder(convertView);
        }
    }

    private class ViewHolder {

        public final ImageView headView;
        public final TextView authorView;
        public final TextView contentView;
        public final TextView infoView;
        public final TextView commentCountView;

        public final View commentButton;
        public final View thumbUpButton;

        public final TextView thumbView;

        public final View itemView;
        public final View nextPageView;
        public final RefreshView refreshView;
        public final TextView refreshTextView;


        public ViewHolder(View convertView) {
            headView = (ImageView) convertView.findViewById(R.id.head_view);
            authorView = (TextView) convertView.findViewById(R.id.author);
            contentView = (TextView) convertView.findViewById(R.id.content);
            infoView = (TextView) convertView.findViewById(R.id.info);
            commentCountView = (TextView) convertView.findViewById(R.id.comment_count);

            commentButton = convertView.findViewById(R.id.comment_button);
            thumbUpButton = convertView.findViewById(R.id.thumb_up_button);

            thumbView = (TextView) convertView.findViewById(R.id.thumb_up_info_view);

            itemView = convertView.findViewById(R.id.item_view);
            nextPageView = convertView.findViewById(R.id.next_pager);

            refreshView = (RefreshView) convertView.findViewById(R.id.next_pager_refresh_view);
            refreshTextView = (TextView) convertView.findViewById(R.id.pager_text_view);
        }
    }
}
